package org.kornero.example;

import android.app.Activity;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.io.IOException;

public class CameraActivity extends Activity implements SurfaceHolder.Callback {

    private static final String TAG = CameraActivity.class.getSimpleName();

    private SurfaceView view;
    private Camera mCamera;

    private volatile boolean mPreviewRunning;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        view = new SurfaceView(this);
        setContentView(view);

        getWindow().setFormat(PixelFormat.TRANSLUCENT);

        // Initialize the surface
        view.getHolder().addCallback(this);
    }

    // Create camera preview.
    public void surfaceCreated(SurfaceHolder holder) {
        Log.e(TAG, "surfaceCreated");
        mCamera = Camera.open();
//        mCamera.startPreview();
    }

    // Change preview's properties (i.e. size or format).
    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        Log.e(TAG, "surfaceChanged");

        // XXX stopPreview() will crash if preview is not running
        if (mPreviewRunning) {
            mCamera.stopPreview();
        }

//        Camera.Parameters p = mCamera.getParameters();
//        p.setPreviewSize(w, h);
//        mCamera.setParameters(p);
        try {
            mCamera.setPreviewDisplay(holder);
        } catch (IOException e) {
            Log.wtf(TAG, e);
        }
        mCamera.startPreview();
        mPreviewRunning = true;
    }

    // Stop the preview.
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.e(TAG, "surfaceDestroyed");
        mCamera.stopPreview();
        mPreviewRunning = false;
        mCamera.release();
    }
}